# -*- coding: utf-8 -*-
"""
cron: 30 */4 * * *
new Env('福利吧签到');
"""

import requests
import re
import os
import sys
from sendNotify import send

def test_site_connectivity(session, url):
    """测试网址连通性并返回状态信息"""
    try:
        response = session.get(f"https://{url}", timeout=10)
        if response.status_code == 200:
            return "✅ 连接成功", True
        else:
            return f"❌ 连接失败 (HTTP状态码: {response.status_code})", False
    except Exception as e:
        return f"❌ 连接失败 ({str(e)})", False

def start(cookie, username):
    try:
        s = requests.Session()
        s.headers.update({
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'Accept-Encoding': 'gzip, deflate, br, zstd',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Upgrade-Insecure-Requests': '1',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'
        })
        
        # 测试所有网址的连通性
        all_urls = ['www.wnflb00.com', 'www.wnflb99.com', 'www.wnflb2023.com']
        site_results = []
        site_available = False
        
        print("开始测试网址连通性:")
        for url in all_urls:
            status, success = test_site_connectivity(s, url)
            site_results.append(f"• {url}: {status}")
            if success:
                site_available = True
                flb_url = url  # 使用第一个可用的网址
                print(f"{url}: {status}")
        
        # 构造网址连接状态报告
        connectivity_report = "📡 网址连接测试结果:\n" + "\n".join(site_results)
        
        # 所有网址都不通的情况
        if not site_available:
            error_msg = f"福利吧签到失败 - 所有网址均无法访问\n用户名: {username}\n\n{connectivity_report}"
            print(error_msg)
            send("福利吧签到失败", error_msg)
            return
        
        # 添加Host和Cookie到头部
        s.headers.update({
            'Host': flb_url,
            'Cookie': cookie
        })
        
        # 访问PC主页
        print(f"\n使用网址: https://{flb_url}")
        response = s.get(f'https://{flb_url}/forum.php?mobile=no')
        user_info = response.text
        
        # 提取用户名
        user_match = re.search(r'title="访问我的空间">(.*?)</a>', user_info)
        parsed_username = user_match.group(1) if user_match else username
        print(f"登录用户名为: {parsed_username}")
        print(f"环境用户名为: {username}")
        
        # 验证用户名匹配
        if parsed_username != username:
            error_msg = f"用户不匹配！解析用户名: {parsed_username} | 环境用户名: {username}"
            print(error_msg)
            final_msg = f"福利吧签到失败\n{connectivity_report}\n\n错误信息: {error_msg}"
            send("福利吧签到失败", final_msg)
            return
        
        # 获取签到链接
        qiandao_match = re.search(r'}function fx_checkin(.*?);', user_info)
        if not qiandao_match:
            error_msg = f"未找到签到链接！用户名: {parsed_username}"
            print(error_msg)
            final_msg = f"福利吧签到失败\n{connectivity_report}\n\n错误信息: {error_msg}"
            send("福利吧签到失败", final_msg)
            return
            
        qiandao_url = qiandao_match.group(1)[47:-2]
        print(f"签到地址: https://{flb_url}/{qiandao_url}")
        
        # 执行签到
        s.get(f'https://{flb_url}/{qiandao_url}')
        
        # 获取最新积分
        response = s.get(f'https://{flb_url}/forum.php?mobile=no')
        user_info = response.text
        
        current_money_match = re.search(r'<a.*? id="extcreditmenu".*?>(.*?)</a>', user_info)
        if current_money_match:
            current_money = current_money_match.group(1)
        else:
            current_money = "无法获取积分信息"
        
        sing_day_match = re.search(r'<div class="tip_c">(.*?)</div>', user_info)
        if sing_day_match:
            sing_day = sing_day_match.group(1)
        else:
            sing_day = "无法获取签到信息"
        
        # 构造成功信息
        success_msg = (
            f"🎉 福利吧签到成功！\n"
            f"👤 用户名: {parsed_username}\n"
            f"📅 {sing_day}\n"
            f"💰 当前积分: {current_money}\n\n"
            f"{connectivity_report}"
        )
        print(success_msg)
        send("福利吧签到成功", success_msg)

    except Exception as e:
        # 尝试获取用户名用于错误报告
        username_display = username or "未知用户"
        
        # 错误报告中包含网址连通性测试结果
        if 'connectivity_report' in locals():
            conn_report = connectivity_report
        else:
            # 如果在测试连通性前就出错，重新获取连通性信息
            conn_report = []
            for url in all_urls:
                status, _ = test_site_connectivity(s, url)
                conn_report.append(f"• {url}: {status}")
            conn_report = "📡 网址连接测试结果:\n" + "\n".join(conn_report)
        
        error_msg = (
            f"⚠️ 福利吧签到失败\n"
            f"👤 用户名: {username_display}\n"
            f"⛔ 错误信息: {str(e)}\n\n"
            f"{conn_report}"
        )
        print(error_msg)
        send("福利吧签到失败", error_msg)

if __name__ == '__main__':
    # 从环境变量获取配置
    cookie = os.getenv("FUBA")
    user_name = os.getenv("FUBAUN")
    
    if not cookie or not user_name:
        error_msg = "未找到环境变量FUBA或FUBAUN，请检查配置！"
        print(error_msg)
        send("福利吧签到配置错误", error_msg)
        sys.exit(1)
    
    start(cookie, user_name)
